package com.xiaoxi.open.design.behavioral.chainofresponsibilitypattern.service.verify;

import com.xiaoxi.open.design.behavioral.chainofresponsibilitypattern.domain.verify.UserInfo;
import lombok.Data;

/**
 * @Author xiaoxi
 * @ProjectName chain_of_responsibility_pattern
 * @PackageName com.xiaoxi.open.design.behavioral.chainofresponsibilitypattern.service.verify
 * @ClassName AbstractLoginCheck
 * @Description TODO
 * @Date 2024/4/24 18:15
 * @Version 1.0
 */
@Data
public abstract class AbstractLoginCheck {

    /**
     * 指向下一个校验抽象类
     */
    protected AbstractLoginCheck next;

    public void execute(UserInfo userInfo) throws Exception {

        // 执行当前阶段
        doHandler(userInfo);

        // 指向下一个责任链
        if (this.next != null) {
            this.next.execute(userInfo);
        }
    }

    /**
     * 用于下面责任链，添加需要校验的方法
     *
     * @throws Exception
     */
    public abstract void doHandler(UserInfo userInfo) throws Exception;

    /**
     * builder 责任链
     */
    public static class Builder {

        private AbstractLoginCheck head;
        private AbstractLoginCheck tail;

        public Builder addHandler(AbstractLoginCheck handler) {
            if (this.head == null) {
                // head用于保存游标
                this.head = handler;
            } else {
                this.tail.setNext(handler);
            }
            // tail 为游标，地址下指，下指
            this.tail = handler;
            return this;
        }

        public AbstractLoginCheck build() {
            return this.head;
        }
    }

}
